package com.it.smartoldb.service;

import com.it.smartoldb.entity.Staff;
import com.it.smartoldb.repository.StaffRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 护理人员服务类
 */
@Service
@Transactional
public class StaffService {

    @Autowired
    private StaffRepository staffRepository;

    /**
     * 创建护理人员
     */
    public Staff createStaff(Staff staff) {
        // 检查身份证号是否已存在
        if (staff.getIdCard() != null && staffRepository.findByIdCard(staff.getIdCard()).isPresent()) {
            throw new RuntimeException("身份证号已存在");
        }
        
        staff.setStatus(Staff.StaffStatus.ACTIVE);
        return staffRepository.save(staff);
    }

    /**
     * 更新护理人员信息
     */
    public Staff updateStaff(Long id, Staff staff) {
        Optional<Staff> existing = staffRepository.findById(id);
        if (!existing.isPresent()) {
            throw new RuntimeException("护理人员信息不存在");
        }
        
        Staff existingStaff = existing.get();
        
        // 检查身份证号是否被其他人使用
        if (staff.getIdCard() != null && 
            !staff.getIdCard().equals(existingStaff.getIdCard()) &&
            staffRepository.findByIdCard(staff.getIdCard()).isPresent()) {
            throw new RuntimeException("身份证号已被其他人使用");
        }
        
        // 更新字段
        existingStaff.setName(staff.getName());
        existingStaff.setGender(staff.getGender());
        existingStaff.setAge(staff.getAge());
        existingStaff.setPosition(staff.getPosition());
        existingStaff.setSkills(staff.getSkills());
        existingStaff.setWorkExperience(staff.getWorkExperience());
        existingStaff.setPhone(staff.getPhone());
        existingStaff.setEmail(staff.getEmail());
        existingStaff.setIdCard(staff.getIdCard());
        existingStaff.setHireDate(staff.getHireDate());
        existingStaff.setSalary(staff.getSalary());
        existingStaff.setAvatarUrl(staff.getAvatarUrl());
        existingStaff.setDescription(staff.getDescription());
        existingStaff.setCertificates(staff.getCertificates());
        
        return staffRepository.save(existingStaff);
    }

    /**
     * 删除护理人员
     */
    public void deleteStaff(Long id) {
        if (!staffRepository.existsById(id)) {
            throw new RuntimeException("护理人员信息不存在");
        }
        staffRepository.deleteById(id);
    }

    /**
     * 根据ID查找护理人员
     */
    public Optional<Staff> findById(Long id) {
        return staffRepository.findById(id);
    }

    /**
     * 分页查询护理人员
     */
    public Page<Staff> findAll(Pageable pageable) {
        return staffRepository.findAll(pageable);
    }

    /**
     * 多条件分页查询
     */
    public Page<Staff> findStaffWithFilters(String name, String idCard, String position,
                                           Staff.StaffStatus status, Pageable pageable) {
        return staffRepository.findStaffWithFilters(name, idCard, position, status, pageable);
    }

    /**
     * 根据职位查找护理人员
     */
    public List<Staff> findByPosition(String position) {
        return staffRepository.findByPosition(position);
    }

    /**
     * 根据状态查找护理人员
     */
    public List<Staff> findByStatus(Staff.StaffStatus status) {
        return staffRepository.findByStatus(status);
    }

    /**
     * 根据姓名模糊查询
     */
    public List<Staff> findByNameContaining(String name) {
        return staffRepository.findByNameContaining(name);
    }

    /**
     * 查询在职人员
     */
    public List<Staff> findActiveStaff() {
        return staffRepository.findByStatusOrderByHireDateDesc(Staff.StaffStatus.ACTIVE);
    }

    /**
     * 根据工作经验查找人员
     */
    public List<Staff> findByMinExperience(Integer minExperience) {
        return staffRepository.findByWorkExperienceGreaterThanEqualAndStatusOrderByWorkExperienceDesc(
                minExperience, Staff.StaffStatus.ACTIVE);
    }

    /**
     * 根据技能查找人员
     */
    public List<Staff> findBySkill(String skill) {
        return staffRepository.findBySkillsContainingAndStatus(skill, Staff.StaffStatus.ACTIVE);
    }

    /**
     * 获取职位统计
     */
    public Map<String, Long> getPositionStatistics() {
        List<Object[]> results = staffRepository.countByPositionAndStatus(Staff.StaffStatus.ACTIVE);
        return results.stream()
                .collect(Collectors.toMap(
                    result -> (String) result[0],
                    result -> (Long) result[1]
                ));
    }

    /**
     * 获取总人数
     */
    public long getTotalCount() {
        return staffRepository.count();
    }

    /**
     * 获取在职人数
     */
    public long getActiveCount() {
        return staffRepository.findByStatus(Staff.StaffStatus.ACTIVE).size();
    }

    /**
     * 停职/离职护理人员
     */
    public Staff deactivateStaff(Long id) {
        Optional<Staff> staff = staffRepository.findById(id);
        if (!staff.isPresent()) {
            throw new RuntimeException("护理人员信息不存在");
        }
        
        Staff s = staff.get();
        s.setStatus(Staff.StaffStatus.INACTIVE);
        return staffRepository.save(s);
    }

    /**
     * 恢复在职状态
     */
    public Staff activateStaff(Long id) {
        Optional<Staff> staff = staffRepository.findById(id);
        if (!staff.isPresent()) {
            throw new RuntimeException("护理人员信息不存在");
        }
        
        Staff s = staff.get();
        s.setStatus(Staff.StaffStatus.ACTIVE);
        return staffRepository.save(s);
    }

    /**
     * 根据身份证号查找护理人员
     */
    public Optional<Staff> findByIdCard(String idCard) {
        return staffRepository.findByIdCard(idCard);
    }
} 